package com.warmlight.voicepacket;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.warmlight.voicepacket.base.BaseActivity;
import com.warmlight.voicepacket.data.PlaydeatalData;
import com.warmlight.voicepacket.data.RecommendFeed;
import com.warmlight.voicepacket.data.eventbus.CollectMoreAudio;
import com.warmlight.voicepacket.data.eventbus.CollectSingleAudio;
import com.warmlight.voicepacket.data.eventbus.NotifyMyPlaylist;
import com.warmlight.voicepacket.dbdata.DBFloatPlaylist;
import com.warmlight.voicepacket.dbmanager.DBFloatPlayListDaoHelp;
import com.warmlight.voicepacket.dbmanager.DBFloatPlayListDetailDaoHelp;
import com.warmlight.voicepacket.utils.ShareCollectCallBackUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by jason on 2018/6/1.
 */

public class CreatePlaylistActivity extends BaseActivity {

    //列表数据
//    private FloatPlayListData mPlaylistData;//播单信息
    private RecommendFeed.DataBean.ListBean mAudioData;//音频信息
    private EditText et_list_name;
    private TextView tv_create,tv_create_cancel;
    private ArrayList<String> audiolist;
    private ArrayList<PlaydeatalData.DataBean.ListBean> mType2List;
    private int addType = 0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_playlist);

        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        if (bundle!= null) {
            if (bundle.containsKey("AudioData")) {
                addType = 0;
                mAudioData = (RecommendFeed.DataBean.ListBean) intent.getSerializableExtra("AudioData");
            } else if (bundle.containsKey("audio_list")) {
                addType = 1;
                audiolist = (ArrayList<String>) bundle.getSerializable("audio_list");
            }else if (bundle.containsKey("net_list")){
                addType = 2;
                mType2List = (ArrayList<PlaydeatalData.DataBean.ListBean>) bundle.getSerializable("net_list");
            }
        }

//        FloatPlayListData AudioData = (FloatPlayListData) getIntent().getSerializableExtra(LIST_ID);
        et_list_name = (EditText) findViewById(R.id.et_list_name);
        tv_create = (TextView) findViewById(R.id.tv_create);
        tv_create_cancel = (TextView) findViewById(R.id.tv_create_cancel);

        tv_create.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final String listname = et_list_name.getText().toString().trim();
                if(TextUtils.isEmpty(listname)){
                    showToast("播单名不能为空");
                    return;
                }
                if(listname.length()>20){
                    showToast("播单名过长");
                    return;
                }

                //查询本地数据库，获取所有本地播单，比对播单名，创建播单名字不能重复
                List<DBFloatPlaylist> playlist = DBFloatPlayListDaoHelp.loadAll(getThis());
                for(DBFloatPlaylist temp : playlist){
                    if(listname.equals(temp.getList_name())){
                        showToast("不能创建名字相同的播单");
                        return;
                    }
                }

                if (addType == 0) {
                    if (mAudioData == null) {
//                    FloatPlayListData data = new FloatPlayListData("",listname,"","0","","");
//                    DBHelper.getInstance(getThis()).addList(data);
                        DBFloatPlaylist data = new DBFloatPlaylist(null, "", listname, "", "0", "", "");
                        DBFloatPlayListDaoHelp.insert(getThis(), data);
                        showToast("创建成功");
                    } else {
                        // 插入audio列表
                        List<RecommendFeed.DataBean.ListBean> list = new ArrayList<>();
                        list.add(mAudioData);
//                    DBHelper.getInstance(getThis()).addAudios(list);
                        DBFloatPlayListDetailDaoHelp.insert(getThis(), list);
                        // 说明音频文件要插入新建表中,表中数量根据计算得来，目前写死为1
//                    FloatPlayListData data = new FloatPlayListData("",listname,"","1",mAudioData.getId(),"");
//                    DBHelper.getInstance(getThis()).addList(data);
                        DBFloatPlaylist data = new DBFloatPlaylist(null, "", listname, "", "1", mAudioData.getId(), "");
                        DBFloatPlayListDaoHelp.insert(getThis(), data);
                        showToast("创建并插入成功");
                        EventBus.getDefault().post(new CollectSingleAudio(mAudioData.getId()));
                        ShareCollectCallBackUtils.collectCallBack(mAudioData.getId(),"1","0");
                    }
                    EventBus.getDefault().post(new NotifyMyPlaylist("notify"));
                    finish();
                }else if (addType == 1){
                    if (audiolist == null){
                        return;
                    }
                    StringBuffer result = new StringBuffer();
                    for(String resultId : audiolist){
                        result.append(resultId);
                        result.append(",");
                    }
                    String s = "";
                    if (result.length() > 0){
                        s = result.substring(0,result.length()-1);
                    }

                    DBFloatPlaylist data = new DBFloatPlaylist(null, "", listname, "", audiolist.size()+"",s , "");
                    DBFloatPlayListDaoHelp.insert(getThis(), data);
                    showToast( "创建并插入成功");
                    EventBus.getDefault().post(new NotifyMyPlaylist("notify"));
                    finish();
                }else if (addType ==2){
                    showProgressDialog();
                    new Thread(new Runnable() {
                        @Override
                        public void run() {


                    List<RecommendFeed.DataBean.ListBean> list = new ArrayList<>();
                    StringBuffer stringBuffer = new StringBuffer();
                    for (int i=0;i<mType2List.size();i++){
                        PlaydeatalData.DataBean.ListBean mbean = mType2List.get(i);
                        stringBuffer.append(mbean.getId());
                        stringBuffer.append(",");

                        RecommendFeed.DataBean.ListBean bean= new RecommendFeed.DataBean.ListBean();

                        bean.setDuration(mbean.getDuration());
                        bean.setCategory_id(mbean.getCategory_id());
                        bean.setId(mbean.getId());
                        bean.setCollect(mbean.getCollect());
                        bean.setShare(mbean.getShare());
                        bean.setStar(mbean.getStar());
                        bean.setTitle(mbean.getTitle());
                        bean.setUrl(mbean.getUrl());
                        bean.setCover_pic(mbean.getPic());
                        bean.setCover_id(mbean.getCover_id());
                        bean.setCover_name(mbean.getCover_name());

                        list.add(bean);
                    }
                    DBFloatPlayListDetailDaoHelp.insert(getThis(), list);
                    String s = "";
                    if (stringBuffer.length()>0){
                        s = stringBuffer.substring(0,stringBuffer.length()-1);
                    }
                    DBFloatPlaylist data = new DBFloatPlaylist(null, "", listname, "", list.size()+"",s, "");
                    DBFloatPlayListDaoHelp.insert(getThis(), data);


                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            hideProgressDialog();
                            showToast( "创建并插入成功");
                            EventBus.getDefault().post(new NotifyMyPlaylist("notify"));
                            EventBus.getDefault().post(new CollectMoreAudio());
                            finish();
                            List<String> ids = new ArrayList<>();
                            for (int i=0;i<mType2List.size();i++){
                                ids.add(mType2List.get(i).getId());
                            }
                            ShareCollectCallBackUtils.collectCallBack(ids,"1","0");
                        }
                    });
                        }
                    }).start();
                }

//                EventBus.getDefault().post(new NotifyMyPlaylist("notify"));
//                finish();

//                List<FloatPlayListDetailData> list = DBHelper.getInstance(getThis()).queryAllAudio();
//                list.add(new FloatPlayListDetailData("asd","asd","asd"));
            }
        });

        tv_create_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });



    }
    private ProgressDialog progressDialog;
    private void showProgressDialog(){
        if (progressDialog == null){
            progressDialog = new ProgressDialog(this,android.R.style.Theme_Material_Light_Dialog_Alert);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progressDialog.setCancelable(false);
            progressDialog.setCanceledOnTouchOutside(false);
            progressDialog.setMessage("加载数据中");
        }

        progressDialog.show();
    }

    private void hideProgressDialog(){
        if (progressDialog != null){
            if (progressDialog.isShowing()){
                progressDialog.dismiss();
            }
        }
    }



    @Override
    public void startActivity(Intent intent) {
        super.startActivity(intent);
        overridePendingTransition(R.anim.slide_bottom_in, R.anim.slide_bottom_out);
    }

    @Override
    public void startActivityForResult(Intent intent, int requestCode, Bundle options) {
        super.startActivityForResult(intent, requestCode, options);
        overridePendingTransition(R.anim.slide_bottom_in, R.anim.slide_bottom_out);
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.slide_bottom_in, R.anim.slide_bottom_out);
    }
}
